import 'dart:io';

import 'package:exif/exif.dart';

class PictureMetaData {
  File file;
  DateTime? time;
  double? latitude;
  double? longitude;

  PictureMetaData(this.file,this.time,this.latitude,this.longitude);


  static Future<PictureMetaData?> readFile(File file) async {
    final bytes = file.readAsBytesSync();
    final exifData = await readExifFromBytes(bytes);

    if(exifData.isEmpty) {
      return null;
    }

    var datetime = exifData['Image DateTime']?.printable;


    // 读取 GPS 信息（纬度）
    final latValues = exifData['GPS GPSLatitude']?.values.toList();
    final latRef = exifData['GPS GPSLatitudeRef']?.printable;

    // 读取 GPS 信息（经度）
    final lonValues = exifData['GPS GPSLongitude']?.values.toList();
    final lonRef = exifData['GPS GPSLongitudeRef']?.printable;

    String? latitude,longitude;

    if (latValues != null && latRef != null && lonValues != null && lonRef != null) {
      final lat = _convertToDegree(latValues);
      final lon = _convertToDegree(lonValues);
      latitude = latRef == 'S' ? (-lat).toString() : lat.toString();
      longitude = lonRef == 'W' ? (-lon).toString() : lon.toString();
    }

    PictureMetaData metaData = PictureMetaData(file, datetime != null ? DateTime.tryParse(datetime) : null,
        latitude != null ? double.tryParse(latitude) : null,
        longitude != null ? double.tryParse(longitude) : null);
    return metaData;
  }

  static double _convertToDegree(List values) {
    final d = values[0].numerator / values[0].denominator;
    final m = values[1].numerator / values[1].denominator;
    final s = values[2].numerator / values[2].denominator;
    return d + (m / 60.0) + (s / 3600.0);
  }

  @override
  String toString() {
    return 'PictureMetaData{file: $file, time: $time, latitude: $latitude, longitude: $longitude}';
  }

}